package com.enhe.gck.fg;

import com.enhe.gck.communal.PublicConstant;
import com.enhe.gck.communal.PublicEntity;
import com.enhe.gck.communal.PublicMethod;
import com.enhe.gck.communal.PublicReturn;
import com.enhe.gck.item.SupplyOrderHWANE16829Item;
import com.enhe.gck.pojo.Material;
import com.enhe.gck.pojo.SupplyOrder;
import com.enhe.gck.pojo.WeightDeduction;
import com.kuangkie.carbon.common.IntegrationMsg;
import com.kuangkie.carbon.common.RemoveRecordInfo;
import com.kuangkie.carbon.fg.RemoveFuncGroup;
import com.kuangkie.carbon.panel.CarbonPanel;
import com.kuangkie.carbon.record.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.kuangkie.carbon.fg.FuncGroupContext;
import com.kuangkie.carbon.fg.ImproveResultFactory;
import com.kuangkie.carbon.fg.SecondRoundImproveFuncGroup;
import com.enhe.gck.CarbonBaseConstant; //模型Code
import com.enhe.gck.CarbonRelationType; //关系类型Code
import com.enhe.gck.item.WeightDeductionHWANE16885Item; // 模型属性Code

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Repository(value = "hwane16885366042330866425862")
public class WeightDeductionHWANE16885BNB implements SecondRoundImproveFuncGroup, RemoveFuncGroup {
	private final Logger logger = LoggerFactory.getLogger(WeightDeductionHWANE16885BNB.class);
	@Override
	public void secondImprove(FuncGroupContext context, ProRecord proRecord, FGRecordComplexus recordComplexus,
			ImproveResultFactory improveResultFactory) {
		WeightDeduction wd=proRecord.getBean(WeightDeduction.class);
		logger.info("QAQ扣款增改业务开始:");
		BigDecimal sumWeight=BigDecimal.ZERO;
		BigDecimal sumWeightDeduction=BigDecimal.ZERO;

		Collection<String> list= proRecord.getGuestRecordCodes(CarbonRelationType.RR_扣重管理_供货订单_供货订单);
		if(list==null||list.isEmpty()){
			PublicMethod.returnMessage(improveResultFactory, PublicReturn.WeightDeduction_1);
			return;
		}
		Map<String,PublicEntity.WeightDeduction> addList=new HashMap();
		for (String x : list) {
			PublicEntity.WeightDeduction we=new PublicEntity.WeightDeduction();
			SupplyOrder supplyOrder=CarbonPanel.getRecordDiscover(CarbonBaseConstant.供货订单_ghdd).getRecordBean(x, SupplyOrder.class);
			we.setWeight(BigDecimal.valueOf(supplyOrder.getActualWeight()));
			we.setMaterial(CarbonPanel.getRecordDiscover(CarbonBaseConstant.物料管理_wlgl)
					.getRecordBean(CarbonPanel.getRecordDiscover(CarbonBaseConstant.供货订单_ghdd).getRelationCorrelation(x).getGuestRecordCode(CarbonRelationType.RR_供货订单_物料名_物料管理), Material.class));
			addList.put(x,we);
			sumWeight=sumWeight.add(we.getWeight());
		}

		logger.info("QAQ-待修改数据{}",addList);
		logger.info("QAQ-是否按照默认计算{}",wd.getIsDefault());
		if(wd.getIsDefault()){
			for (String key : addList.keySet()) {
				PublicEntity.WeightDeduction info=addList.get(key);
				try {
					if(info.getMaterial().getIsRatio()){
						BigDecimal weightDeduction=PublicMethod.multiplyBigDecimal(addList.get(key).getWeight(),PublicMethod.divideBigDecimal(info.getMaterial().getRatio(),100), PublicConstant.weightDecimals,null);
						sumWeightDeduction=sumWeightDeduction.add(weightDeduction);
						addList.get(key).setWeightDeduction(weightDeduction);
					}else {
						sumWeightDeduction=sumWeightDeduction.add(BigDecimal.valueOf(info.getMaterial().getWeight()));
						addList.get(key).setWeightDeduction(BigDecimal.valueOf(info.getMaterial().getWeight()));
					}
				}catch (Exception e){
					logger.info("QAQ-订单产品数据异常:{}",key);
				}
			}
		}else {
			logger.info("QAQ-是否按照比例{}",wd.getIsRatio());
			if(wd.getIsRatio()){
				for (String key : addList.keySet()) {
					BigDecimal weightDeduction=PublicMethod.multiplyBigDecimal(addList.get(key).getWeight(),PublicMethod.divideBigDecimal(wd.getRatio(),100), PublicConstant.weightDecimals,null);
					addList.get(key).setWeightDeduction(weightDeduction);
					sumWeightDeduction=sumWeightDeduction.add(weightDeduction);
				}
			}else{
				sumWeightDeduction=BigDecimal.valueOf(wd.getWeight());
				BigDecimal sumWeightDeductionLs=BigDecimal.valueOf(wd.getWeight());
				Iterator<String> iterator = addList.keySet().iterator();
				while (iterator.hasNext()) {
					BigDecimal weightDeduction;
					String key=iterator.next();
					PublicEntity.WeightDeduction value = addList.get(key);

					if(!iterator.hasNext()){
						addList.get(key).setWeightDeduction(sumWeightDeductionLs);
						//最后一个
					}else {
						weightDeduction=PublicMethod.multiplyBigDecimal(sumWeightDeduction,PublicMethod.divideBigDecimal(value.getWeight(),sumWeight,PublicConstant.weightDecimals, RoundingMode.DOWN),PublicConstant.weightDecimals,RoundingMode.DOWN);
						sumWeightDeductionLs=sumWeightDeductionLs.subtract(weightDeduction);
						addList.get(key).setWeightDeduction(weightDeduction);
					}

				}
			}
		}
		//设置重量
		improveResultFactory.getCurrentProRecordOpsBuilder()
				.putAttribute(WeightDeductionHWANE16885Item.基本属性组_重量, sumWeightDeduction);

		//扣重修改状态
		Map<String,PublicEntity.WeightDeduction> deleteList = new HashMap<>();
		if(!proRecord.isNew()){
			Collection<String> oldCodeList=CarbonPanel.getRecordDiscover(CarbonBaseConstant.扣重管理_kzgl).getProRecord(wd.getRecordCode()).getGuestRecordCodes(CarbonRelationType.RR_扣重管理_供货订单_供货订单);
			if(oldCodeList!=null&&!oldCodeList.isEmpty()){
				oldCodeList.forEach(ha->{
					if(!addList.containsKey(ha)){
						deleteList.put(ha,null);
					}
				});
			}
		}
		updateGh(addList,true);
		updateGh(deleteList,false);
		logger.info("QAQ扣款增改业务结束：");
	}

	private void updateGh(Map<String,PublicEntity.WeightDeduction> list,boolean isTrue){
        for (String key : list.keySet()) {
            PublicEntity.WeightDeduction value = list.get(key);
			IntegrationMsg integrate = CarbonPanel.getFGRecordBuilder(CarbonBaseConstant.供货订单_ghdd, key)
					.putAttribute(SupplyOrderHWANE16829Item.基本属性组_是否扣重, isTrue)
					.putAttribute(SupplyOrderHWANE16829Item.基本属性组_扣除重量, isTrue?value.getWeightDeduction():BigDecimal.ZERO)
					.integrate();
			logger.info("QAQ同步设置扣重状态:{} {}",integrate.getRecordCode(),isTrue?value.getWeightDeduction():BigDecimal.ZERO);
        }
	}

	@Override
	public boolean beforeRemove(FuncGroupContext funcGroupContext, RemoveRecordInfo removeRecordInfo) {
		Collection<String> list=removeRecordInfo.getRecordCodes();
		if(list!=null&& !list.isEmpty()){
			list.forEach(x->{
				Collection<String> haveList=CarbonPanel.getRecordDiscover(CarbonBaseConstant.扣重管理_kzgl).getProRecord(x).getGuestRecordCodes(CarbonRelationType.RR_扣重管理_供货订单_供货订单);
				if(haveList!=null&&!haveList.isEmpty()){
					Map<String,PublicEntity.WeightDeduction> deleteList = new HashMap<>();
					haveList.forEach(code->{
						deleteList.put(code,null);
					});
					updateGh(deleteList,false);
				}
			});
		}


		return true;
	}

	@Override
	public boolean afterRemove(FuncGroupContext funcGroupContext, RemoveRecordInfo removeRecordInfo) {
		return false;
	}
}
